<?php

namespace app\admin\controller;

use app\admin\logic\Menus;
use nx\Data;
use think\Cache;
use think\Db;
use app\admin\model\AuthRule;
use think\exception\DbException;
use tree\Tree;

class Menu extends Admin
{
    /**
     * 菜单显示
     * @return mixed
     */
    public function index()
    {
        $data = model('AuthRule')->order('sort asc')->select();

        $data = Data::tree($data, 'title', 'id', 'pid');
        $this->assign('authrule', $data);
        $this->getMiddleRule();
        return $this->fetch();
    }

    /**
     * 新增菜单
     * @return mixed
     */
    public function add()
    {
        $this->getAuthRule();
        if (input('id')) {
            $this->assign('pid', input('id'));
        }
        return $this->fetch();
    }

    /**
     * 编辑菜单
     * @return mixed
     */
    public function edit()
    {
        $this->getAuthRule();
        input('id') ? $id = input('id') : $this->error('缺少参数');
        $info = Db::name('AuthRule')->where(['id' => $id])->find();
        $this->assign('info', $info);
        return $this->fetch();
    }

    /**
     *获取所有的菜单
     * @internal
     */
    public function getAuthRule()
    {
        $data = model('AuthRule')->order('sort asc')->select();
        $data = Data::tree($data, 'title', 'id', 'pid');
        $this->assign('authrule', $data);
    }

    /**
     *添加菜单权限
     */
    public function addrun()
    {
        if (!request()->isAjax()) {
            $this->error('提交方式不正确', url('admin/menu/index'));
        } else {
            $menu = new AuthRule();
            $data = input('post.');
            !empty($data['status']) ?: $data['status'] = 0;
            !empty($data['mstatus']) ?: $data['mstatus'] = 2;
            $data['notcheck'] === '0' ?: $data['notcheck'] = 1;
            $pid = Db::name('auth_rule')->where(array('id' => input('pid')))->field('level')->find();
            $level = $pid['level'] + 1;
            $data['level'] = $level;
            $result = $menu->validate('menu')->allowField(true)->save($data);
            if (false === $result) {
                // 验证失败 输出错误信息
                $this->error($menu->getError());
            } else {
                Cache::clear('menu');
                if (!empty($data['mid'])) {
                    Db::name('auth_rule_middle')->where(['id' => $data['mid']])->delete();
                }
                $this->success('权限添加成功', url('admin/menu/index'));
            }
        }
    }

    /**
     *添加菜单权限
     */
    public function editrun()
    {
        if (!request()->isAjax()) {
            $this->error('提交方式不正确', url('admin/menu/index'));
        } else {
            $menu = new AuthRule();
            $data = input('post.');
            !empty($data['status']) ?: $data['status'] = 0;
            !empty($data['mstatus']) ?: $data['mstatus'] = 2;
            $data['notcheck'] === '0' ?: $data['notcheck'] = 1;
            $old_pid = input('old_pid');
            $old_level = input('old_level', 0, 'intval');
            $pid = input('pid');
            $level_diff = 0;
            //判断是否更改了pid
            if ($pid != $old_pid) {
                $level = Db::name('auth_rule')->where('id', $pid)->value('level') + 1;
                $level_diff = ($level > $old_level) ? ($level - $old_level) : ($old_level - $level);
            } else {
                $level = $old_level;
            }
            $result = $menu->allowField(true)->validate('menu')->isUpdate(true)->save($data);
            if ($result !== false) {
                if ($pid != $old_pid) {
                    //更新子孙级菜单的level
                    $auth_rule = Db::name('auth_rule')->order('sort')->select();
                    $tree = new Tree();
                    $tree->init($auth_rule, ['parentid' => 'pid']);
                    $ids = $tree->get_childs($auth_rule, $data['id'], true, false);
                    if ($ids) {
                        if ($level > $old_level) {
                            Db::name('auth_rule')->where('id', 'in', $ids)->setInc('level', $level_diff);
                        } else {
                            Db::name('auth_rule')->where('id', 'in', $ids)->setDec('level', $level_diff);
                        }
                    }
                }
                Cache::clear('menu');
                $this->success('菜单修改成功', url('admin/menu/index'));
            } else {
                // 验证失败 输出错误信息
                $this->error($menu->getError());
            }
        }
    }

    /**
     * 删除权限菜单
     * @return \think\response\Json
     * @author: Huang
     */
    public function del()
    {
        $id = $this->request->param('id', 0);
        if (empty($id)) {
            $this->error('请选择要操作的数据!');
        }
        if (Db::name('AuthRule')->where('pid', $id)->find()) {
            $arr = ['status' => 2, 'info' => '该节点有子节点不能删除'];
        } else {
            if (AuthRule::destroy($id)) {
                Cache::clear('menu');
                $arr = ['status' => 1, 'info' => '删除成功'];
            } else {
                $arr = ['status' => 0, 'info' => '删除失败'];
            }
        }
        return json($arr);
    }

    /**
     * 权限(后台菜单)通过复制添加
     */
    public function rule_copy()
    {
        $this->getAuthRule();
        $admin_rule = Db::name('auth_rule')->where(array('id' => input('id')))->find();
        $this->assign('info', $admin_rule);
        return $this->fetch('copy');
    }

    /**
     * 权限(后台菜单)显示/隐藏
     */
    public function menus_rule_state()
    {
        $id = input('id');
        $statusone = Db::name('auth_rule')->where(array('id' => $id))->value('status');//判断当前状态情况
        if ($statusone == 1) {
            $statedata = array('status' => 0);
            Db::name('auth_rule')->where(array('id' => $id))->setField($statedata);
            Cache::clear('menu');
            $this->success('关闭');
        } else {
            $statedata = array('status' => 1);
            Db::name('auth_rule')->where(array('id' => $id))->setField($statedata);
            Cache::clear('menu');
            $this->success('开启');
        }
    }

    /**
     *自动生成菜单到中间表
     */
    public function importRule()
    {
        $menu = new Menus();
        $rule = Db::name('auth_rule')->field('name')->select();
        $rule = collect($rule)->flatten(1)->all();
        $re = collect($menu->execute())->flatten(1)->filter(function ($item) use ($rule) {
            if (!in_array($item['name'], $rule)) {
                return $item;
            }
        })->all();
        foreach ($re as $v) {
            try {
                Db::name('auth_rule_middle')->insert($v);
            } catch (DbException $exception) {
                continue;
            }
        }
        $this->success('规则导入成功', 'index');
    }

    /**
     * 获取rule中间表
     * @internal
     */
    public function getMiddleRule()
    {
        $data = Db::name('auth_rule_middle')->where(['isadd' => 1])->select();
        $this->assign('middlerule', $data);
    }

    /**
     * 从中间表新增菜单
     * @return mixed
     */
    public function addedit()
    {
        input('id') ? $id = input('id') : $this->error('缺少参数');
        $info = Db::name('AuthRuleMiddle')->where(['id' => $id])->find();
        $this->assign('info', $info);
        $this->getAuthRule();
        return $this->fetch();
    }

    /**
     * 删除权限菜单
     * @return \think\response\Json
     * @author: Huang
     */
    public function delmiddle()
    {
        $id = $this->request->param('id', 0);
        if (empty($id)) {
            $this->error('请选择要操作的数据!');
        }
        if (Db::name('AuthRuleMiddle')->where(['id' => $id])->delete()) {
            $arr = ['status' => 1, 'info' => '删除成功'];
        } else {
            $arr = ['status' => 0, 'info' => '删除失败'];
        }
        return json($arr);
    }
}
